package leetcode.day_2020_2021_1_18_2021_1_24;

import java.util.Arrays;
import java.util.HashMap;

/**
 * https://leetcode-cn.com/problems/two-sum/
 * 1. 两数之和
 */
public class Leetcode0001 {
    public static void main(String[] args) {
        int[] arr = {2,7,11,15};
        int target = 9;
        System.out.println(Arrays.toString(twoSum01(arr, target)));
        System.out.println(Arrays.toString(twoSum02(arr, target)));
    }

    /**
     * 暴力法
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum01(int[] nums, int target) {
        for(int i=0; i<nums.length; i++) {
            for(int j=1; j<nums.length; j++) {
                if(nums[i]+nums[j] == target) {
                    if(i != j) {
                        return new int[]{i, j};
                    }
                }
            }
        }
        return new int[]{-1, -1};
    }

    public static int[] twoSum02(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i=0; i<nums.length; i++) {
            map.put(nums[i], i);
        }
        for(int i=0; i<nums.length; i++) {
            int value = target - nums[i];
            if(map.containsKey(value) && map.get(value)!=i) {
                return new int[] {i, map.get(value)};
            }
        }
        return new int[]{-1, -1};
    }
}
